﻿#include "maskwidget.h"
#include "qapplication.h"
#include <QDebug>
#include <QLabel>

MaskWidget *MaskWidget::self = 0;
MaskWidget::MaskWidget(QWidget *parent) : QWidget(parent)
{
    mainWidget = 0;
//    setOpacity(0.5);
//    setBgColor(QColor(255, 255, 255));

    this->setAttribute(Qt::WA_ShowModal, true);
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
    //绑定全局事件,过滤弹窗窗体进行处理
    qApp->installEventFilter(this);

    setMouseTracking(true);

    m_imgLabel = new QLabel(this);
    m_imgLabel->setGeometry(20,20,150, 150);
    m_imgLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true);

    QImage *img=new QImage;
    img->load("/tmp/tmp1.png");
    QPixmap pixmap = QPixmap::fromImage(*img);
    QPixmap fitpixmap = pixmap.scaled(150, 150, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    m_imgLabel->setPixmap(fitpixmap);
    delete(img);

}

void MaskWidget::setMainWidget(QWidget *mainWidget)
{
    if (this->mainWidget != mainWidget){
        this->mainWidget = mainWidget;
    }
}

void MaskWidget::setDialogNames(const QStringList &dialogNames)
{
    if (this->dialogNames != dialogNames){
        this->dialogNames = dialogNames;
    }
}

void MaskWidget::setOpacity(double opacity)
{
    this->setWindowOpacity(opacity);
}

void MaskWidget::setBgColor(const QColor &bgColor)
{
    QPalette palette = this->palette();
    palette.setBrush(QPalette::Background, bgColor);
    this->setPalette(palette);
}

void MaskWidget::showEvent(QShowEvent *)
{
    if (mainWidget != 0) {
        this->setGeometry(mainWidget->geometry());
        QTimer::singleShot(100,this,[=](){
            this->setOpacity(0.3);
        });
    }
}

bool MaskWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::Show) {
        if (dialogNames.contains(obj->objectName())) {
            this->show();
        }
    } else if (event->type() == QEvent::Hide) {
        if (dialogNames.contains(obj->objectName())) {
            this->hide();
        }
    }else if(event->type() == QEvent::Move){
        QRect rect(mainWidget->geometry());
        rect.setRect(mainWidget->parentWidget()->geometry().x() +mainWidget->x(), mainWidget->parentWidget()->geometry().y()+mainWidget->y(), rect.width(), rect.height());
        qDebug() << rect;
        this->setGeometry(rect);
    }

    return QObject::eventFilter(obj, event);
}

void MaskWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        this->hide();
    }
}

void MaskWidget::mouseMoveEvent(QMouseEvent * e)
{
    m_imgLabel->move(e->x()-m_imgLabel->width()/2,e->y()-m_imgLabel->height()/2);
}
